<script lang="ts" setup>
import { ref, computed, onBeforeUnmount } from "vue";
import { useStore } from "@/stores/data";

const store = useStore();

// ===== 倒计时状态 =====
const COUNTDOWN = 60;
const remain = ref(0);        // 剩余秒数，0 表示可再次发送
const sending = ref(false);   // 接口请求中的瞬时状态
let timerId: number | null = null;

const phoneOk = computed(() => {
  const p = store.register?.phone?.trim() || "";
  return p.length >= 6; // 如需严格校验可换为正则
});

const canSend = computed(() => {
  return !!store.register && phoneOk.value && !sending.value && remain.value === 0;
});

const btnText = computed(() => {
  return remain.value > 0 ? `${remain.value}s 后重试` : "获取";
});

function startCountdown() {
  remain.value = COUNTDOWN;
  if (timerId) {
    clearInterval(timerId);
    timerId = null;
  }
  timerId = window.setInterval(() => {
    if (remain.value <= 1) {
      remain.value = 0;
      if (timerId) {
        clearInterval(timerId);
        timerId = null;
      }
    } else {
      remain.value -= 1;
    }
  }, 1000);
}

onBeforeUnmount(() => {
  if (timerId) clearInterval(timerId);
  timerId = null;
});

// ===== 获取验证码 =====
const getCode = async () => {
  if (!canSend.value) return;
  try {
    sending.value = true;
    const res = await store.getCodeAct(store.register.phone, "register");
    console.log(res);
    startCountdown(); // 成功后开始倒计时
  } catch (error) {
    console.log(error);
    // 失败不启动倒计时，允许再次点击
  } finally {
    sending.value = false;
  }
};

// ===== 注册（保持你原逻辑） =====
const doRegister = async () => {
  try {
    await store.registerAct();
  } catch (e) {
    console.log(e);
  }
};
</script>

<template>
  <div>
    <h1>注册</h1>

    <input
      placeholder="请输入手机号"
      type="text"
      v-model="store.register.phone"
    />

    <input
      placeholder="请输入验证码"
      type="text"
      v-model="store.register.code"
    />

    <button :disabled="!canSend" @click="getCode">
      {{ btnText }}
    </button>

    <input
      placeholder="请输入密码"
      type="text"
      v-model="store.register.password"
    />

    <input
      placeholder="请输入邀请码（非必填）"
      type="text"
      v-model="store.register.invite_code"
    />

    <button @click="doRegister">注册</button>
  </div>
</template>

<style lang="scss" scoped>
/* 不写样式；按需自行添加 */

</style>
